package org.ziegler.hotfix;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class HotFixUtils {


    /**
     * 获取分割的第一个值，用“TAB”分割字符串
     * @param row 一行数据
     * @return 第一个值的字符串
     */
    public static String getSplitFirstValue(String row) {
        final String[] split = row.split("\t");
        return split.length == 0 ? "" : split[0];
    }

    /**
     * 写入多行数据
     * @param fileName 文件名（全路径）
     * @param lines 多行数据，数据格式{@link String}
     * @param append 追加方式写入
     * @throws IOException 写入文件是吧
     */
    public static void writeMultiline(String fileName, Collection<String> lines, boolean append) {
        File file = new File(fileName);
        writeMultiline(file, lines, append);
    }

    /**
     * 写入多行数据
     * @param file {@link File}
     * @param lines 多行数据，数据格式{@link String}
     * @throws IOException 写入文件是吧
     */
    public static void writeMultiline(File file, Collection<String> lines, boolean append) {
        try(final FileWriter fileWriter = new FileWriter(file, Charset.forName("UTF-8"), append);
            final BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            for (String line : lines) {
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            System.out.println("写入文件[" + file.getName() + "]失败 = " + e.getMessage());
        }
    }

    /**
     * 遍历文件的每一行
     * @param fileName 文件路径
     * @throws IOException 文件读取失败可能抛出的异常
     */
    public static List<String> readMultiLine(String fileName) {
        File file = new File(fileName);
        return readMultiLine(file);
    }

    /**
     * 读取多行数据
     * @param file 文件 {@link File}类型
     * @throws IOException 文件读取失败可能抛出的异常
     */
    public static List<String> readMultiLine(File file) {
        List<String> lines = new ArrayList<>();
        try(final FileReader fileReader = new FileReader(file, Charset.forName("UTF-8"));
            final BufferedReader bufferedReader = new BufferedReader(fileReader)) {
            String str = bufferedReader.readLine();
            while (str != null) {
                lines.add(str);

                // 读取下一行
                str = bufferedReader.readLine();
            }
        } catch (IOException e) {
            System.out.println("读取文件[" + file.getName() + "]失败 = " + e.getMessage());
        }

        return lines;
    }

}
